"use client"

import React, { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import dynamic from 'next/dynamic'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { Eye, EyeOff, LogIn, User, Lock } from 'lucide-react'
import { useAuth } from '@/contexts/auth-context'

export default function LoginPage() {
  const router = useRouter()
  const { login, isAuthenticated, isLoading: authLoading } = useAuth()
  const [mounted, setMounted] = useState(false)
  const [formData, setFormData] = useState({
    username: '',
    password: ''
  })
  const [showPassword, setShowPassword] = useState(false)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  // 确保组件已挂载，避免hydration问题
  useEffect(() => {
    setMounted(true)
  }, [])

  // 如果已经登录，重定向到仪表板
  useEffect(() => {
    if (isAuthenticated && mounted) {
      router.push('/dashboard')
    }
  }, [isAuthenticated, mounted, router])

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (!e?.target) return
    
    const { name, value } = e.target
    if (!name) return

    setFormData(prev => ({
      ...prev,
      [name]: value
    }))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    // 清除之前的错误
    setError('')
    
    // 验证输入
    if (!formData.username?.trim()) {
      setError('请输入用户名')
      return
    }
    
    if (!formData.password?.trim()) {
      setError('请输入密码')
      return
    }

    setLoading(true)

    try {
      console.log('开始登录...', { username: formData.username })
      
      const response = await login(formData.username.trim(), formData.password.trim())
      
      console.log('登录响应:', response)
      
      if (response?.success && response?.token && response?.user) {
        console.log('登录成功，准备跳转...')
        // useAuth已经处理了token和用户信息的保存
        // 跳转到仪表板
        router.push('/dashboard')
      } else {
        const errorMsg = response?.message || '登录失败，请检查用户名和密码'
        console.error('登录失败:', errorMsg)
        setError(errorMsg)
      }
    } catch (err) {
      console.error('登录异常:', err)
      setError('登录失败，请稍后重试')
    } finally {
      setLoading(false)
    }
  }

  const togglePasswordVisibility = () => {
    setShowPassword(prev => !prev)
  }

  // 避免hydration不匹配，在组件未挂载时显示简单版本
  if (!mounted || authLoading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900 mx-auto"></div>
          <p className="mt-2 text-gray-600">加载中...</p>
        </div>
      </div>
    )
  }

  // 如果已经认证，显示加载状态
  if (isAuthenticated) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900 mx-auto"></div>
          <p className="mt-2 text-gray-600">登录成功，正在跳转...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex items-center justify-center p-4">
      <div className="w-full max-w-md">
        {/* Logo and Title */}
        <div className="text-center mb-8">
          <div className="w-16 h-16 bg-gradient-to-br from-slate-700 to-slate-900 rounded-2xl flex items-center justify-center mx-auto mb-4">
            <span className="text-amber-400 font-bold text-2xl">创</span>
          </div>
          <h1 className="text-2xl font-bold text-gray-900 mb-2">创业者之家</h1>
          <p className="text-gray-600">后台管理系统</p>
        </div>

        <Card className="shadow-lg border-0">
          <CardHeader className="space-y-1 pb-6">
            <CardTitle className="text-xl text-center flex items-center justify-center space-x-2">
              <LogIn className="h-5 w-5" />
              <span>管理员登录</span>
            </CardTitle>
          </CardHeader>
          <CardContent>
            <form onSubmit={handleSubmit} className="space-y-4">
              {/* Error Alert */}
              {error && (
                <Alert variant="destructive">
                  <AlertDescription>{error}</AlertDescription>
                </Alert>
              )}

              {/* Username Input */}
              <div className="space-y-2">
                <label className="text-sm font-medium text-gray-700">用户名</label>
                <div className="relative">
                  <User className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                  <Input
                    type="text"
                    name="username"
                    value={formData.username}
                    onChange={handleInputChange}
                    placeholder="请输入用户名"
                    className="pl-10"
                    required
                    disabled={loading}
                    autoComplete="username"
                  />
                </div>
              </div>

              {/* Password Input */}
              <div className="space-y-2">
                <label className="text-sm font-medium text-gray-700">密码</label>
                <div className="relative">
                  <Lock className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                  <Input
                    type={showPassword ? "text" : "password"}
                    name="password"
                    value={formData.password}
                    onChange={handleInputChange}
                    placeholder="请输入密码"
                    className="pl-10 pr-10"
                    required
                    disabled={loading}
                    autoComplete="current-password"
                  />
                  <button
                    type="button"
                    onClick={togglePasswordVisibility}
                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 focus:outline-none"
                    disabled={loading}
                    tabIndex={-1}
                  >
                    {showPassword ? (
                      <EyeOff className="h-4 w-4" />
                    ) : (
                      <Eye className="h-4 w-4" />
                    )}
                  </button>
                </div>
              </div>

              {/* Remember Me and Forgot Password */}
              <div className="flex items-center justify-between">
                <label className="flex items-center">
                  <input
                    type="checkbox"
                    className="rounded border-gray-300 text-slate-600 focus:ring-slate-500 h-4 w-4"
                    disabled={loading}
                  />
                  <span className="ml-2 text-sm text-gray-600">记住我</span>
                </label>
                <button
                  type="button"
                  className="text-sm text-slate-600 hover:text-slate-800 focus:outline-none"
                  disabled={loading}
                >
                  忘记密码？
                </button>
              </div>

              {/* Login Button */}
              <Button
                type="submit"
                className="w-full"
                disabled={loading}
              >
                {loading ? (
                  <div className="flex items-center">
                    <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                    登录中...
                  </div>
                ) : (
                  <>
                    <LogIn className="h-4 w-4 mr-2" />
                    登录
                  </>
                )}
              </Button>
            </form>

            {/* Footer */}
            <div className="mt-6 text-center">
              <p className="text-xs text-gray-500">
                © 2025 创业者之家. 保留所有权利.
              </p>
            </div>
          </CardContent>
        </Card>

        {/* Demo Credentials */}
        <div className="mt-6 p-4 bg-blue-50 rounded-lg border border-blue-200">
          <h3 className="text-sm font-medium text-blue-900 mb-2">测试账户信息</h3>
          <div className="text-xs text-blue-800 space-y-1">
            <p>用户名: admin</p>
            <p>密码: admin123</p>
            <p className="text-blue-600 mt-2">💡 开发环境会自动fallback到模拟数据</p>
          </div>
        </div>
      </div>
    </div>
  )
}